package com.aso114.project.mvp.activity.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.adapter.HistoryAdapter;
import com.aso114.project.base.BaseFragment;
import com.aso114.project.bean.HistoryBean;
import com.aso114.project.bean.QuestionBaseBean;
import com.aso114.project.bean.QuestionBean;
import com.aso114.project.bean.questioncontentListBean;
import com.aso114.project.exam.ExpositionTestActivity;
import com.aso114.project.exam.PracticeReportActivity;
import com.aso114.project.exam.QuestionTestActivity;
import com.aso114.project.mvp.LoginSP;
import com.aso114.project.mvp.activity.ExamResultsActivity;
import com.aso114.project.mvp.model.CallBack;
import com.aso114.project.mvp.model.CommentModel;
import com.aso114.project.util.Constant;
import com.aso114.project.util.Helper;
import com.aso114.project.util.HelperBean;
import com.aso114.project.util.ToastUtils;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 练习历史未完成 与 完成-----行测
 * Created by asus on 2018/11/9.
 */

public class PracticeHistoryOneFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, SwipeMenuRecyclerView.LoadMoreListener, HistoryAdapter.OnItemClickListener {
    @BindView(R.id.history_left)
    TextView historyLeft;
    @BindView(R.id.history_right)
    TextView historyRight;
    @BindView(R.id.history_null_ly)
    LinearLayout historyNullLy;
    @BindView(R.id.history_listView)
    SwipeMenuRecyclerView historyListView;
    @BindView(R.id.history_refresh_ly)
    SwipeRefreshLayout historyRefreshLy;
    Unbinder unbinder;
    Dialog dialog;
    Intent intent;
    HistoryAdapter historyAdapter;
    QuestionBean qdata;
    List<HistoryBean.Data> mData = new ArrayList<>();
    public int historytype = 1;// 1未完成  2完成
    //刷新
    private boolean isRefresh = false;

    private int pageNo = 1;
    private String status = "9";

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_practice_history;
    }

    @Override
    protected void initView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        historyListView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        historyAdapter = new HistoryAdapter(getActivity(), mData, historytype);
        historyListView.setAdapter(historyAdapter);
        // 刷新
        historyRefreshLy.setOnRefreshListener(this);
        // 加载
        historyListView.useDefaultLoadMore();

        historyListView.setLoadMoreListener(this);
        historyAdapter.setOnItemClickListener(this);
        historyLeft.performClick();
    }

    private void getData() {
        if (isRefresh) {
            historyRefreshLy.setRefreshing(true);
        }
        CommentModel.getInstant().get_history_list(pageNo, LoginSP.getInstance().getUserAreaId(), Constant.adutst, status, new CallBack() {
            @Override
            public void onSuccess(Object o, boolean isSuccess, String msg) {
                Helper.gotoLogin(isSuccess);
                List<HistoryBean.Data> bean = (List<HistoryBean.Data>) o;
                if (historyRefreshLy == null) {
                    return;
                }
                if (isRefresh) {
                    pageNo = 1;
                    historyRefreshLy.setRefreshing(false);
                    mData.clear();
                }
                if (bean == null || bean.size() == 0) {
                    // 一定要调用这个方法，否则不会触发加载更多。
                    // 第一个参数：表示此次数据是否为空，假如你请求到的list为空(== null || list.size == 0)，那么这里就要true。
                    // 第二个参数：表示是否还有更多数据，根据服务器返回给你的page等信息判断是否还有更多，这样可以提供性能，如果不能判断则传true。
                    if (pageNo == 1) {
                        historyNullLy.setVisibility(View.VISIBLE);
                        historyRefreshLy.setVisibility(View.GONE);
                        historyListView.loadMoreFinish(true, true);
                        historyAdapter.notifyDataSetChanged();
                    } else {


                        historyListView.loadMoreFinish(true, true);
                        historyAdapter.notifyDataSetChanged();
                        ToastUtils.showToast(getActivity(), "已加载全部数据");
                    }

                } else {
                    historyNullLy.setVisibility(View.GONE);
                    historyRefreshLy.setVisibility(View.VISIBLE);
                    mData.addAll(bean);
                    historyAdapter.notifyDataSetChanged();
                    historyListView.loadMoreFinish(false, true);
                }
            }

            @Override
            public void onFailure(String fail) {
                historyRefreshLy.setRefreshing(false);
                Helper.showToast(fail);
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void addOnClick() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.history_left, R.id.history_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.history_left:
                historyLeft.setTextColor(getResources().getColor(R.color.aff6559));
                historyRight.setTextColor(getResources().getColor(R.color.a333333));
                historytype = 1;
                historyAdapter.setHistoryType(historytype);
                pageNo = 1;
                isRefresh = true;
                status = "9";
                getData();
                break;
            case R.id.history_right:
                //加载完成的
                historyLeft.setTextColor(getResources().getColor(R.color.a333333));
                historyRight.setTextColor(getResources().getColor(R.color.aff6559));
                historytype = 2;
                historyAdapter.setHistoryType(historytype);
                pageNo = 1;
                isRefresh = true;
                status = "1";
                getData();
                break;
        }
    }

    @Override
    public void onRefresh() {
        // 刷新
        // 下拉刷新
        pageNo = 1;
        isRefresh = true;
        getData();
    }

    @Override
    public void onLoadMore() {
        // 加载
        // 上拉加载
        pageNo++;
        isRefresh = false;
        getData();
    }

    @Override
    public void onItemClick(View view, final int postion) {
        final View dialogview = getActivity().getLayoutInflater().inflate(
                R.layout.loading_view, null);
        dialog = new Dialog(getActivity(), R.style.dialogStyle);
        dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        dialog.getWindow().setGravity(Gravity.CENTER);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);//设置是否可以按退回键取消
        dialog.show();


        CommentModel.getInstant().get_history_bank(LoginSP.getInstance().getUserAreaId(), mData
                .get(postion).getPaperId(), Constant.adutst, new CallBack() {
            @Override
            public void onSuccess(Object o, boolean isSuccess, String msg) {

                dialog.cancel();
                Helper.gotoLogin(isSuccess);//token失效去重新登陆
                qdata = (QuestionBean) o;
                if (qdata == null) {
                    Helper.showToast("获取数据失败，稍后尝试");
                    return;
                }
                System.out.println("题库大小111===" + qdata.getPaperTitle());
                System.out.println("题库数组大小===" + qdata.getQuestionBaseList().get(0)
                        .getQuestionList().size());
                if (historytype == 2) {  // 完成跳转到报告
                    EventBus.getDefault().postSticky(HelperBean.getBaseBean(qdata));
                    intent = new Intent(getActivity(), PracticeReportActivity.class);
                    startActivity(intent);
                } else {
                    EventBus.getDefault().postSticky(qdata);
                    intent = new Intent(getActivity(), QuestionTestActivity.class);
                    intent.putExtra("isHistory", true);
                    if (mData.get(postion).getExamPaperType().equals(Constant.title_type1)) {//考点练习
                        Constant.title_tv = "1";
                        intent.putExtra("is_exam", false);
                        intent.putExtra("isAnalysis", true);
                    }
                    if (mData.get(postion).getExamPaperType().equals(Constant.title_type2)) {//章节练习
                        Constant.title_tv = "2";
                        intent.putExtra("is_exam", false);
                        intent.putExtra("isAnalysis", true);
                    }
                    if (mData.get(postion).getExamPaperType().equals(Constant.title_type3)) {//真题模考
                        Constant.title_tv = "3";
                        intent.putExtra("is_exam", true);
                    }
                    if (mData.get(postion).getExamPaperType().equals(Constant.title_type4)) {//巩固练习
                        Constant.title_tv = "4";
                        intent.putExtra("is_exam", true);
                    }

                    startActivity(intent);
                }
            }

            @Override
            public void onFailure(String fail) {
                ToastUtils.showToast(getActivity(), "获取题库失败");
                dialog.cancel();
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        // 刷新
        // 下拉刷新
        pageNo = 1;
        isRefresh = true;
        getData();
    }
}
